package cn.toma.core.web.jsonconfig;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;

import java.io.IOException;
import java.util.List;
import java.util.Set;

/**
 * @author zqx
 * @version 1.0.0
 * @ClassName MyBeanSerializerModifier.java
 * @Description
 * @createTime 2019年08月28日 21:25:00
 */
public class MyBeanSerializerModifier extends BeanSerializerModifier
{
	/**
	 * 对集合 数组 为空 null 的情况处理
	 */
	class MyNullArrayJsonSerializer extends JsonSerializer
	{
		@Override
		public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException
		{
			if (o == null) {
				jsonGenerator.writeStartArray();
				jsonGenerator.writeEndArray();
			}

		}
	}

	/**
	 * 对null 字符处理
	 */
	class MyNullJsonSerializer extends JsonSerializer
	{
		@Override
		public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException
		{
			jsonGenerator.writeString("");
		}
	}


	/**
	 * 数组类型
	 */

	private JsonSerializer nullArrayJsonSerializer = new MyNullArrayJsonSerializer();

	/**
	 * 字符串等类型
	 */
	private JsonSerializer nullJsonSerializer = new MyNullJsonSerializer();

	@Override
	public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties)
	{
		//循环所有的beanPropertyWriter
		for (int i = 0; i < beanProperties.size(); i++) {
			BeanPropertyWriter writer = (BeanPropertyWriter) beanProperties.get(i);
			//判断字段的类型，如果是array，list，set则注册nullSerializer
			//给writer注册一个自己的nullSerializer
			if (isArrayType(writer)) writer.assignNullSerializer(this.nullArrayJsonSerializer);
			else writer.assignNullSerializer(this.nullJsonSerializer);
		}
		return beanProperties;
	}


	/**
	 * 判断是什么类型
	 *
	 * @param writer
	 * @return
	 */
	boolean isArrayType(BeanPropertyWriter writer)
	{
		Class clazz = writer.getPropertyType();
		return clazz.isArray() || clazz.equals(List.class) || clazz.equals(Set.class);
	}
}
